﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using EM.Repository.utility;
using System.Web.UI.HtmlControls;

namespace AlternateProject
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        public string APPROOT = ""; AppPathFinder finder = new AppPathFinder();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["pageId"] != null)
                this.CreateSubMenu(Convert.ToInt32(Session["pageId"]));


            APPROOT = finder.GetApplicationPath();

            if (!Page.IsPostBack)
            {
                this.CreateMenu();

                this.GetHistory();
            }
        }

        Authentication ua = new Authentication();

        private void CreateMenu()
        {
            if (ua.hasSessionAuthentication())
            {
                SqlCommand cmd = new SqlCommand();
                DbHelper dbhelper = new DbHelper();
                string sSQL = "";
                sSQL += @" SELECT P.PAGEID, MENUNAME, PARENTPAGEID, PAGETYPE, NULL AS PAGEURL 
                            FROM TBLPAGE P, TBLPAGE_L L 
                            WHERE P.PAGEID = L.PAGEID 
                            AND STATUS = 'A' 
                            AND L.LANGCODE = @LANGCODE 
                            AND GETDATE() BETWEEN STARTDATE AND DATEADD(D, 1, ISNULL(ENDDATE,'31/12/2099')) 
                            AND DISPLAYMENUFLG = 'Y'  
                            AND PAGETYPE = 'M' ";
                if (!ua.UserIsAnAdmin(Session["USERID"].ToString()))
                {
                    sSQL += @" AND P.PAGEID IN (SELECT PAGEID FROM TBLROLEPAGE_COMPILED WHERE ROLEID IN (	SELECT UR.ROLEID FROM TBLUSERROLE UR, TBLROLE R WHERE USERID = @USERID AND UR.ROLEID = R.ROLEID AND R.STATUS = 'A' AND GETDATE() BETWEEN UR.STARTDATE AND ISNULL(UR.ENDDATE,'01/01/2099') AND GETDATE() BETWEEN R.STARTDATE AND ISNULL(R.ENDDATE,'01/01/2099'))) 
                             AND DBO.fnGetPageChildItemCount(P.PAGEID, @USERID, GETDATE()) > 0";
                }

                sSQL += " ORDER BY PAGEORDER ";
                cmd.CommandText = sSQL;
                cmd.Parameters.Add("LANGCODE", SqlDbType.NVarChar).Value = Session["LANGCODE"].ToString();
                cmd.Parameters.Add("USERID", SqlDbType.Int).Value = Convert.ToInt32(Session["USERID"].ToString());

                DataTable dt = dbhelper.GetDataTable(cmd, "");

                rptMainMenu.DataSource = dt;
                rptMainMenu.DataBind();
            }
        }

        protected void rptSubMenu_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                HtmlAnchor aMenu = e.Item.FindControl("aMenu") as HtmlAnchor;
                DataRowView row = e.Item.DataItem as DataRowView;

                aMenu.HRef = row["PAGEURL"].ToString();

                if (Request.QueryString["pgid"] != null)
                {
                    if (row["PAGEID"].ToString() == Request.QueryString["pgid"].ToString())
                        aMenu.Attributes.Add("id", "active");
                }
            }
        }

        protected void rptMainMenu_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "GetSubMenu")
            {
                Session["pageId"] = e.CommandArgument;
                CreateSubMenu(Convert.ToInt32(e.CommandArgument));
            }
        }

        private void CreateSubMenu(int PageId)
        {
            SqlCommand cmd = new SqlCommand();
            string sSQL = @"
                SELECT P.PAGEID, MENUNAME, NULL PARENTPAGEID, PAGETYPE, 
                CASE WHEN PAGEURL IS NULL THEN '' ELSE @APPROOT + '/' + PAGEURL + '?pgid=' + convert(nvarchar,P.PAGEID) END AS PAGEURL, PAGEORDER 
                FROM TBLPAGE P, TBLPAGE_L L  
                WHERE P.PAGEID = L.PAGEID  
                AND STATUS = 'A'  
                AND L.LANGCODE = @LANGCODE
                AND GETDATE() BETWEEN STARTDATE AND DATEADD(d, 1, ISNULL(ENDDATE,'31/12/2099')) AND DISPLAYMENUFLG = 'Y'   
                AND PARENTPAGEID = @PAGEID ";

            if (!ua.UserIsAnAdmin(Session["USERID"].ToString()))
            {
                sSQL += @" AND P.PAGEID IN (SELECT PAGEID FROM TBLROLEPAGE_COMPILED WHERE ROLEID IN (SELECT ROLEID FROM TBLUSERROLE WHERE USERID = @USERID AND GETDATE() BETWEEN STARTDATE AND DATEADD(d,1, ISNULL(ENDDATE,CONVERT(DATETIME,'30/12/2099'))))) 
                                AND DBO.fnGetPageChildItemCount(P.PAGEID, @USERID, GETDATE()) > 0";
            }
            sSQL += @" UNION ALL 
                SELECT P.PAGEID, MENUNAME, PARENTPAGEID, PAGETYPE, 
                CASE WHEN PAGEURL IS NULL THEN '' ELSE  @APPROOT + '/' + PAGEURL + '?pgid=' + convert(nvarchar,P.PAGEID) END AS PAGEURL, PAGEORDER 
                FROM TBLPAGE P, TBLPAGE_L L  
                WHERE P.PAGEID = L.PAGEID  
                AND STATUS = 'A'  
                AND L.LANGCODE = @LANGCODE
                AND GETDATE() BETWEEN STARTDATE AND DATEADD(d, 1, ISNULL(ENDDATE,'31/12/2099'))  
                AND DISPLAYMENUFLG = 'Y'   ";

            if (!ua.UserIsAnAdmin(Session["USERID"].ToString()))
            {
                sSQL += " AND P.PAGEID IN (SELECT PAGEID FROM TBLROLEPAGE_COMPILED WHERE ROLEID IN (SELECT ROLEID FROM TBLUSERROLE WHERE USERID = @USERID AND GETDATE() BETWEEN STARTDATE AND DATEADD(d,1, ISNULL(ENDDATE,CONVERT(DATETIME,'30/12/2099'))))) ";
            }

            sSQL += @" AND PARENTPAGEID IN ( 
                 		SELECT P.PAGEID 
                 		FROM TBLPAGE P 
                 		WHERE 1 = 1 
                 		AND STATUS = 'A'
                 		AND GETDATE() BETWEEN STARTDATE AND DATEADD(d, 1, ISNULL(ENDDATE,'31/12/2099'))  
                 		AND DISPLAYMENUFLG = 'Y'   
                 		AND PARENTPAGEID =  @PAGEID ";
            if (!ua.UserIsAnAdmin(Session["USERID"].ToString()))
            {
                sSQL += " AND P.PAGEID IN (SELECT PAGEID FROM TBLROLEPAGE_COMPILED WHERE ROLEID IN (SELECT ROLEID FROM TBLUSERROLE WHERE USERID = @USERID AND GETDATE() BETWEEN STARTDATE AND DATEADD(d,1, ISNULL(ENDDATE,CONVERT(DATETIME,'30/12/2099'))))) ";
            }
            sSQL += @" ) 
                        ORDER BY PAGEORDER";

            DataTable dtSubMenu = new DataTable();
            cmd = new SqlCommand();
            cmd.CommandText = sSQL;
            cmd.Parameters.Add("@LANGCODE", SqlDbType.NVarChar).Value = Session["LANGCODE"].ToString();
            cmd.Parameters.Add("@USERID", SqlDbType.Int).Value = Convert.ToInt32(Session["USERID"].ToString());
            cmd.Parameters.AddWithValue("@APPROOT", this.APPROOT == "" ? this.finder.GetApplicationPath() : this.APPROOT);
            cmd.Parameters.AddWithValue("@PAGEID", PageId);

            DbHelper helper = new DbHelper();
            dtSubMenu = helper.GetDataTable(cmd, "");
            rptSubMenu.DataSource = dtSubMenu;
            rptSubMenu.DataBind();
        }

        protected void btnLogout_Click(object sender, EventArgs e)
        {
            DbHelper dsrv = new DbHelper();
            SqlCommand cmd = new SqlCommand();
            string sSQL = "";
            sSQL += " UPDATE TBLSESSIONHEADER SET";
            sSQL += "  ENDDATE = GETDATE()";
            sSQL += " WHERE SESSIONHEADERID = @SESSIONHEADERID ";
            cmd.Parameters.Add("@SESSIONHEADERID", SqlDbType.BigInt).Value = Session["SESSIONHEADERID"].ToString();
            cmd.CommandText = sSQL;
            dsrv.ExecuteNonQuery(cmd);

            Session.Abandon();
            Response.Redirect("~/");
        }

        protected void rptHistory_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            HtmlAnchor aPage = e.Item.FindControl("aPage") as HtmlAnchor;
            DataRowView row = e.Item.DataItem as DataRowView;
            aPage.HRef = APPROOT + "/" + row["PAGEURL"];
        }

        private void GetHistory()
        {
            if (Session["HISTORY"] != null)
            {
                List<int> history = Session["HISTORY"] as List<int>;

                string IDs = "";

                foreach (int item in history)
                {
                    IDs += item + ",";
                }
                if (IDs != "")
                {
                    string sSQL = @"SELECT P.PAGEID, PL.PAGENAME, P.PAGEURL FROM TBLPAGE P, TBLPAGE_L PL
                                    WHERE P.PAGEID = PL.PAGEID
                                    AND PL.LANGCODE = 'TR' ";
                    sSQL += " AND P.PAGEID IN (" + IDs.TrimEnd(',') + ")";

                    DbHelper helper = new DbHelper();
                    DataTable dt = helper.GetDataTable(sSQL, "");
                    rptHistory.DataSource = dt;
                    rptHistory.DataBind();
                }

            }
        }
    }
}
